<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\bootstrap\ActiveForm;
use yii\helpers\ArrayHelper;
use Symfony\Component\Console\Helper\FormatterHelper;
/* @var $this yii\web\View */
/* @var $searchModel app\models\search\RecordInfoQNSearchModel */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'CTI录音文件';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="record-info-qn-index">
    <div class="form-group">
        <form action="index" id="callTimeClass" target="blank">
            <input class='btn btn-success' type='button' value='根据通话时间筛选' id = 'getTime'/>
        </form>
    </div>
    <?= $this->render('/common/timer_piker')?>
    <?= $this->render('/common/dialog')?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'caption' =>
            "<h4><a href='#'>统计</a>：总计：<a href='#'>".
            $dataProvider->totalCount
            ."</a>条，已分类文件总数：<a href='#'>".
            (new \app\models\ArcProgress())->find()->count()
            ."</a>条；未分类文件总数：<a href='#'>".
            ($dataProvider->totalCount-(new \app\models\ArcProgress())->find()->count())
            ."</a>条；今天已分类数：<a href='#'>".
            ($todayTotalCount['problem']+ $todayTotalCount['noproblem'])
            ."</a>条；有问题数：<a href='#'>".
            $todayTotalCount['problem']
            ."</a>条；无问题数：<a href='#'>".
            $todayTotalCount['noproblem']
            ."</a>条；".
            "</h4>"
        ,  //设置显示最下面的footer
        'showFooter' => true,  //设置显示最下面的footer
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            ['attribute' => 'EmployeeNumber',
                'filter' => '<input type="text" class="form-control" name="ThingRecordFileSearchModel[EmployeeNumber]" placeholder="输入分机号查询" >',
                'footer' => '
                    <input id="num"  type="number" href="#" class="btn btn-default btn-xs btn-delete" placeholder="每页显示的条数"/>
                ',
            ],
            ['attribute' => 'Caller',
                'filter' => '<input type="text" class="form-control" name="ThingRecordFileSearchModel[Caller]" placeholder="输入电话号码查询" >',
                'footer' => '
                    <form action="index" method="post">
                        <input name="newestOne" value="true" hidden="hidden"/>
                        <a href="?page='.$newestPage.'&per-page='.$pages->pageSize.'" class="btn btn-info" placeholder="">跳到最新训练的一条</a>
                    </form>
                ',
            ],
            ['attribute' => 'TallTimeStart',
                'value' =>
                function ($model){
                    return date('Y年m月d日 H:i:s', strtotime($model->TallTimeStart));
                },
                'options'=>[
                    'width'=>'15%',
                ]
            ],
            ['attribute' => 'Filepath',
                'value' =>
                function ($model){
                    $Filepath = $model->Filepath;
                    $filePath = \common\helps\Tools::getFilePath($Filepath);
                    if(strlen($filePath)>20){
                        $tempStr = mb_substr($filePath, 0,20).'...';   //主要通过此种方式实现
                        return '<div title="'.$filePath.'">'.$tempStr.'</div>';
                    }else{
                        return $filePath.'';
                    }
                },
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                        'width'=>'16%',
                ]
            ],
            ['attribute' => '分类模型',
                'value' =>
                function($model){
                    try {
                       $result = $model->getArcProgress()->one()->arc_classify;
                       if($result==0)return '<div style="color:#dd4b39">未分类</div>';
                       $sql = "select name from arc_classify where id = $result";
                       $res = Yii::$app->db->createCommand($sql)->queryOne();
                       return '<div style="color:#00a65a">'.$res['name']."</div>";
                    }catch (Exception $e){
                        return '';
                    }
                },
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'14%',
                ]
            ],
            ['attribute' => 'progress',
                'value' =>
                function($model){
                    try {
                        $progress = $model->getArcProgress()->one()->progress;
                        if ($progress == 0){
                            return '<div style="color:#f39c12">未训练</div>';
                        }elseif ($progress == 1) {
                            return '<div style="color:#00c0ef">正在训练</div>';
                        }elseif($progress == 2) {
                            return '<div style="color:#00a65a">训练完成</div>';
                        }else{
                            return '<div style="color:#dd4b39">无状态</div>';
                        }
                    }catch (\Exception $e){
                        return '<div style="color:#dd4b39">无状态</div>';
                    }
                },
                'label'=>'训练状态',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                     'width'=>'8%',
                ]
            ],
            ['attribute' => 'arc_classify_status',
                'value' =>
                function($model){
                    try {
                        $arc_classify_status = $model->getArcProgress()->one()->arc_classify_status;
                        if ($arc_classify_status == 2){
                            return '<div style="color:green">无情绪</div>';
                        }elseif ($arc_classify_status == 1) {
                            return '<div style="color:red">有情绪</div>';
                        }else{
                            return '<div style="color:#dd4b39">无状态</div>';
                        }
                    }catch (\Exception $e){
                        return '<div style="color:#dd4b39">无状态</div>';
                    }
                },
                    'label'=>'情绪有无',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                     'width'=>'8%',
                ]
            ],
            ['attribute' => 'arc_classify_status',
                'value' =>
                    function($model){
                        $arcProgressModel = $model->getArcProgress();
                        if (!empty($arcProgressModel)){
                            $arcProgress = $arcProgressModel->one();
                            if(!empty($arcProgress)){
                                return date("Y年m月d日 H:i:s",$arcProgressModel->one()->create_time);
                            }else{
                                return "";
                            }
                        }else{
                            return "";
                        }
                    },
                'label'=>'训练时间',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'13%',
                ]
            ],
            ['attribute' => 'arc_language',
                'value' =>
                    function ($model,$url,$key){
                        try {
                              $arcProgress = $model->getArcProgress();
                            if (!empty($arcProgress)) {
                                $progressModel = $arcProgress->one();
                                if (!empty($progressModel)) {
                                    $arcClassify = $progressModel->getArcClassify();
                                    if (!empty($arcClassify)) {
                                        $arc_classify = $arcClassify->one();
                                        $arc_problems_arr = explode('|', $arc_classify->content);
                                        $arc_language = $progressModel->arc_language;
                                        $result = \common\helps\Tools::recogniseBaiduToHtml($arc_problems_arr,$arc_language);
                                        $formatterResult = \common\helps\Tools::recogniseBaiduToHtmlFormatter($result);
                                        $results = "";
                                        foreach ($result as $k=>$v){
                                            $results = $results.$v[0]."。\r\n";
                                        }
                                        //将结果格式化，有。号就换行
                                            $var = '<div class="btn-group" id="hover'.$key.'" style="max-height: 40px;overflow: auto" title="'.htmlspecialchars($results).'">
                                                    <a href="#" >'."点击查看识别结果".'
                                                    </a>
                                              <div class="dropdown-menu " style="padding:10px;max-height: 300px;max-width: 300px;overflow: auto" role="menu">
                                              </div>
                                            </div>';
                                            $hidden = '<div hidden="hidden" id="formatterResult'.$key.'">'.$formatterResult.'</div>';
                                            $script = "
                                            <script>
                                                $('#hover$key').click(function() {
                                                  $('#asrRes').removeAttr('hidden');
                                                  $('#chatId').html($('#formatterResult$key').html());
                                                });
                                            </script>
                                            ";
                                            return $var.$hidden.$script.'';
                                    }
                                }else{
                                    return "";
                                }
                            }else{
                                return "";
                            }
                        }catch (\Exception $e){
                            return '<div style="color:red">无识别结果</div>';
                        }
                    },
                'label'=>'识别结果',
                'format' => 'raw',//表示显示的是html格式的
                'options'=>[
                    'width'=>'12%',
                ]
            ],
            ['class' => 'yii\grid\ActionColumn',//下面是新增加的按按钮
                'header' => '操作',
                'template' => '{view}  {play}  {arc}',
                'buttons' => [
                        'view'=> function ($url, $model, $key) {
                            $url = 'view?id='.$key.'&page='.(isset($_GET['page'])?$_GET['page']:0).'&per-page='.(isset($_GET['per-page'])?$_GET['per-page']:0);
                            $result = Html::a('<span class="btn btn-success fa fa-sticky-note-o">详情</span>&nbsp;', $url,
                                    ['id' => 'view',
                                    'title' => '查看详细信息'] );
                            return $result;
                        },
                        'play' => function ($url, $model, $key) {
                            $Filepath = $model->Filepath;
                            $progress = $model->getArcProgress()->one();
                            $filepath = \common\helps\Tools::getFilePath($Filepath);
                            if(!empty($progress) ){
                                if($progress->progress == 4){
                                    $resStr = '<a id="modal_'.$key.'"
                                    class="btn btn-danger fa fa-danger"
                                    href="#"
                                    title="该文件不存在，需要到CTI中重新上传">无文件</a>&nbsp;';
                                }else{
                                        $resStr = '<a id="modal_'.$key.'"
                                    class="btn btn-info fa fa-download"
                                    href="../common/play-download?httpFilePath='.htmlspecialchars($filepath).'"
                                    title="请点击该机器人进行修改以及查看" data-toggle="modal"
                                    data-target="#create-modal">下载</a>&nbsp;';
                                }
                            }else{
                                $resStr = '<a id="modal_'.$key.'"
                                    class="btn btn-info fa fa-download"
                                    href="../common/play-download?httpFilePath='.htmlspecialchars($filepath).'"
                                    title="请点击该机器人进行修改以及查看" data-toggle="modal"
                                    data-target="#create-modal">下载</a>&nbsp;';
                            }
                            return $resStr.'';
                        },
                        'arc' => function ($url, $model, $key) {
                            $Filepath = $model->Filepath;
                            $filepath = \common\helps\Tools::getFilePath($Filepath);
                            $progress = $model->getArcProgress()->one();
                            $resStr = "";
                            if(!empty($progress)){
                                if($progress->progress == 0){
                                    $resStr = '<a id="modal_' . $key . '" class="glyphicon glyphicon-play" href="../thing-record-file/identify-result?progressId="'.$key.' title="进行识别分类" data-toggle="modal" data-target="#create-modal"></a>';
                                }elseif($progress->progress == 1){
//                                    $resStr = '<a id="modal_' . $key . '" class="glyphicon glyphicon-stop" href="#" title="进行识别分类" data-toggle="modal" data-target="#create-modal"></a>';
                                }
                            }else{
                                $resStr = "";
//                                $resStr = '<a id="modal2_' . $key . '" class="glyphicon glyphicon-play" href="../common/arc-one?httpFilePath='.htmlspecialchars($filepath).'" title="进行识别分类"  data-toggle="modal" data-target="#create-modal"></a>';
                            }
                            return $resStr.'';
                        },
                ],
                'options' => [
                    'width' => '15%',
                ],
            ],

        ],
        'pager'=>[
			'firstPageLabel'=>"第一页",
			'lastPageLabel'=>'最后一页',
    	],

    ]); ?>
</div>
<div id="asrRes" class="box box-warning direct-chat direct-chat-warning" style="width:500px;position:absolute;
top:20px;z-index: 99999;left: 50%;margin-left: -250px;top:50%;margin-top:-200px;" hidden="hidden">
    <div class="box-header with-border">
        <h3 class="box-title">识别结果（点击该页面进行关闭）</h3>
        <div class="box-tools pull-right">
            <button type="button" class="btn btn-box-tool" data-toggle="tooltip" title="" data-widget="chat-pane-toggle" data-original-title="Contacts">
                <i class="fa fa-comments"></i></button>
            </button>
        </div>
    </div>
    <!-- /.box-header -->
    <div class="box-body">
        <!-- Conversations are loaded here -->
        <div class="direct-chat-messages" id="chatId">
            大叔大婶
        </div>
        <!--/.direct-chat-messages-->

    </div>
    <!-- /.box-body -->
</div>
<?= $this->render('/common/dialog_iframe2',['path2'=>'../common/identify-result'])?>
<script type="text/javascript">
    $('#num').blur(function(){//当鼠标失去焦点是触发事件,实现用户自定义分页
       var url = "<?= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] ?>";
       $.ajax({
            type:'post',
            async:true,
            url:url,
            data:{pageSize:$('#num').val()},
            success:function(data){
                window.location.reload();
            },
            error:function(error){

            }
       });
    });
    $('#newestOne').click(function() {
        $('#newestOne').submit();
    });
    $('#asrRes').click(function(){
        $(this).attr('hidden','hidden');
    });
    // $('.file_path').on('click',function () {
    //    //var filePath = $('.file_path').attr('href');
    //    //alert(filePath);
    //     $.ajax({
    //         type:'post',
    //         async:true,
    //         url:"http://www.advanced.com/common/ArcOne",
    //         data:{filePath:$('.file_path').attr('href')},
    //         success:function(data){
    //             //window.location.reload();
    //         },
    //         error:function(error){
    //
    //         }
    //     });
    // });
</script>